package com.bnz.controller;

import com.bnz.entity.PageResult;
import com.bnz.entity.R;
import com.bnz.entity.Student;
import com.bnz.mapper.StudentMapper;
import com.bnz.service.StudentService;
import com.bnz.vo.StudentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

//@ResponseBody
//@Controller
        //二化一
@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;
    @RequestMapping("/hello")
    public String hello(Model mode){
        mode.addAttribute("username","张三");
        return "welcome";
    }
    @GetMapping("/list")
    public String list(Model model){
        //查询学生
        List<Student> students = studentService.findAll();
        //放入model中
        model.addAttribute("students",students);
        //返回前端
        return "/student/list";
    }
    //查询所有学生
    @GetMapping("/findAll")
    public ModelAndView findAll(){
        //茶学生
        List<Student> all = studentService.findAll();
        //放到模型中
        ModelAndView modelAndView = new ModelAndView("student/list","students",all);
        //返回前端
        return modelAndView;
    }

    /**
     * 通过R对象返回
     * @return
     */
    @GetMapping("lists")
    public R find(){
        List<Student> all = studentService.findAll();
        return R.ok().data("lists",all);
    }

    /**
     * 分页
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("findByPage/{page}/{pageSize}")
    public R findByPage(@PathVariable int page,@PathVariable int pageSize){
        //分页查找
        PageResult<Student> pr = studentService.findByPage(page,pageSize);
            //返回r
            return R.ok().data("pr",pr);

    }

    /**
     * 条件查询
     * @param page
     * @param pageSize
     * @param vo
     * @return
     */
    @PostMapping("search/{page}/{pageSize}")
    public R search(@PathVariable int page ,@PathVariable int pageSize,
                    @RequestBody(required = false) StudentVo vo){
        PageResult<Student> pr = studentService.search(page,pageSize,vo);
        //返回
        return R.ok().data("pr",pr);
    }

    /**
     * 添加
     * @param student
     * @return
     */
    @RequestMapping("add")
    public R save(@RequestBody Student student){
            studentService.save(student);
            return R.ok().message("添加陈共");
        }
    /**
     * 修改
     * @param student
     * @return
     */
    @RequestMapping("update")
    public R update(@RequestBody Student student){
            studentService.update(student);
        return R.ok().message("修改陈共");

    }
}
